//
//  TKIMChangeFaceViewController.m
//  test2
//
//  Created by TryHone on 17/1/17.
//  Copyright © 2017年 TryHone. All rights reserved.
//

#import "TKIMChangeFaceViewController.h"
#import "TKIMAccountModel.h"
#import "TKIMAccountStyle1TableViewCell.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>

#define TEMP_USER_FACE @"TEMP_USER_FACE"

@interface TKIMChangeFaceViewController ()<UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>

@property(nonatomic,strong) UIImagePickerController *imagePicker;
@property(nonatomic,assign) BOOL isAlbum;
@property(nonatomic,strong) TKIMLayerUtils *layerUtils;

//选择的图片
@property(nonatomic,strong) UIImage* seleteimage;//图片选择

@end

@implementation TKIMChangeFaceViewController{
    UITableView *_tableView;
    NSMutableArray *_dataSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [super viewDidLoad];
    self.navigationItem.title=@"更换头像";
    [self buildUI];
    [self buildData];
    
    _layerUtils = [[TKIMLayerUtils alloc] initWithContent:self.view];
}


#pragma mark--构建数据源
-(void)buildData{
    //清除数据
    [_dataSource removeAllObjects];
    TKIMUser* user=[TKIMManager shareInstance].loginUser;
    
    
    TKIMAccountModel * data1 = [[TKIMAccountModel alloc] init];
    data1.lefttitle = @"头像";
    data1.rightimagename = user.thumbPhotoUrl?user.thumbPhotoUrl:(user.originalPhotoUrl?user.originalPhotoUrl:@"");
    data1.imageDta=_seleteimage;
    
    _dataSource = [NSMutableArray array];
    [_dataSource addObject:@[data1]];
}
#pragma mark--构建UI
-(void)buildUI{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView=[self footView];
    self.view.backgroundColor=[TKUIHelper colorWithHexString:@"#444a5a"];
    if(IOS7_OR_LATER){
        _tableView.backgroundColor =[TKUIHelper colorWithHexString:@"#F7F7F7"];
    }
    [self.view addSubview:_tableView];
}

-(UIView*)footView{
    UIView * view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44+20)];
    [view addSubview:[self confimeBtn]];
    return view;
}

-(UIButton*)confimeBtn{
    
    UIButton*  btn=[[UIButton alloc] initWithFrame:CGRectMake(10, 20, [UIScreen mainScreen].bounds.size.width-2*10, 40)];
    btn.backgroundColor=[TKUIHelper colorWithHexString:@"#26aee1"];
    [btn setTitle:@"确认" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(saveFace:) forControlEvents:UIControlEventTouchUpInside];
    btn.layer.masksToBounds=YES;
    btn.layer.cornerRadius=5;
    
    return btn;
    
}


-(void)saveFace:(id)btn{
    [_layerUtils showLoading:YES withLabel:@"正在上传..."];
    UIImage * image = _seleteimage;
    
    
    if (image) {
        
        [[TKIMManager shareInstance] uploadUserHeadImage:image complete:^(NSObject *obj)
         {
             [_layerUtils showLoading:NO];
            [_layerUtils showTip:@"上传成功"];
             [TKIMManager shareInstance].loginUser.thumbPhotoUrl=(NSString*)obj;

         } process:^(NSInteger totalBytes, NSInteger bytesWritten)
         {
             NSLog(@"%ld======%ld",totalBytes,bytesWritten);
         } fail:^(NSError *error)
         {
             [_layerUtils showLoading:NO];
             [_layerUtils showTip:@"上传失败"];
         }];
        
        
    }else{
        
        [_layerUtils showLoading:NO];
        [_layerUtils showTip:@"上传失败,请选择图片后重试"];
        
    }
    
    
}

#pragma mark--表格代理
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [_dataSource count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray * arr=[_dataSource objectAtIndex:section];
    return [arr count];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.section==0) {
        
         TKIMAccountStyle1TableViewCell* cell = [TKIMAccountStyle1TableViewCell cellWithTableView:tableView];
        TKIMAccountModel * data=_dataSource[indexPath.section][indexPath.row];
        cell.datamodle=data;
        return cell;
    }else{
        NSString *Identifier = [NSString stringWithFormat:@"settingcell%ld",indexPath.section];
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:Identifier];
            [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            cell.textLabel.font = [UIFont systemFontOfSize:15.0f];
            
        }
        TKIMAccountModel * data=_dataSource[indexPath.section][indexPath.row];
        cell.textLabel.text = data.lefttitle;
        cell.detailTextLabel.text=data.righttitle;
        return cell;
        
    }
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return  45;
}


//选中
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self uploadImage];
    
}


-(void)uploadImage{
    
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照上传",@"相册上传", nil];
    [sheet showInView:self.view];
    
    
}

-(UIImagePickerController *)imagePicker
{
    if (!_imagePicker)
    {
        _imagePicker = [[UIImagePickerController alloc] init];
        
        if (!_isAlbum)
        {
            _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            //设置使用哪个摄像头，这里设置为后置摄像头
            _imagePicker.cameraDevice=UIImagePickerControllerCameraDeviceRear;
        }
        else
        {
            _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
        _imagePicker.delegate = self;
        _imagePicker.allowsEditing=YES;//允许编辑
        
    }
    return _imagePicker;
}



-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    //获取原始照片
    UIImage *image;
    //如果允许编辑则获得编辑后的照片，否则获取原始照片
    if (self.imagePicker.allowsEditing)
    {
        //获取编辑后的照片
        image=[info objectForKey:UIImagePickerControllerEditedImage];
    }
    else
    {
        //获取原始照片
        image=[info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
    if (image)
    {
        _seleteimage=image;
        [self buildData];
        [_tableView reloadData];
    }
    
    [self dismissViewControllerAnimated:YES completion:^
     {
         self.imagePicker = nil;
     }];
}




- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:^
     {
         self.imagePicker = nil;
     }];
    
}


- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        NSString * mediaType = AVMediaTypeVideo;
        AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied||![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
        {
            [_layerUtils showTip:@"没有调用相机的权限，请到设置中打开"];
            return;
        }
        _isAlbum = NO;
        [self presentViewController:self.imagePicker animated:YES completion:nil];
    }
    else if(buttonIndex == 1)
    {
        
        _isAlbum = YES;
        [self presentViewController:self.imagePicker animated:YES completion:nil];
    }
}


-(void)dealloc{
    _seleteimage=nil;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
